package example.step1;

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class ExternalObject implements Externalizable {

    @Override
    public String toString() {
        return "ExternalObject [name=" + name + ", age=" + age + "]";
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    private String name;
    private int age;

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject("[name=" + getName() + "]");
        out.writeInt(getAge());
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {
        this.name = (String)in.readObject();
        this.age = in.readInt();
    }
    // 运行函数
    public static void main(String args[]) throws Exception{
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("E:\\idea-workspace\\gitee\\demo\\serializable\\src\\main\\java\\objfile\\exserial.obj"));
        // 序列化对象
        ExternalObject person = new ExternalObject();
        person.setAge(27);
        person.setName("Lang Yu");
        // 数据的序列化写入
        out.writeObject(person); // writeExternal 自动执行
        out.close();
        // 反序列化对象
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("E:\\idea-workspace\\gitee\\demo\\serializable\\src\\main\\java\\objfile\\exserial.obj"));
        // 数据的反序列化读取
        ExternalObject target = (ExternalObject)in.readObject();
        System.out.println(target); // readExternal 自动执行
        in.close();
    }
}
